package com.liu.yubi.aop;

import com.liu.yubi.annotation.AuthCheck;
import com.liu.yubi.common.ErrorCode;
import com.liu.yubi.exception.BusinessException;
import com.liu.yubi.model.entity.User;
import com.liu.yubi.model.enums.UserRoleEnum;
import com.liu.yubi.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验 AOP
 *

 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //需要的权限
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue (loginUser.getUserRole ());
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue (mustRole);

        //必须有权限才可以通过
        if (StringUtils.isNotBlank (mustRole)){
            //未登录
            if (ObjectUtils.isEmpty (loginUser)){
                throw new BusinessException (ErrorCode.NOT_LOGIN_ERROR);
            }
            //封禁状态
            if (UserRoleEnum.BAN.equals(userRoleEnum)){
                throw new BusinessException (ErrorCode.NO_AUTH_ERROR,"该账号处于封禁状态！");
            }
            assert mustRoleEnum != null;
            if (!mustRoleEnum.equals(userRoleEnum)){
                throw new BusinessException (ErrorCode.NO_AUTH_ERROR);
            }
        }

        //校验通过，放行
        return joinPoint.proceed ();
    }
}

